package kr.hyosang.android.penfo.board;

import java.util.ArrayList;

import kr.hyosang.android.penfo.BoardBase;
import kr.hyosang.android.penfo.Definition;
import kr.hyosang.android.penfo.HttpImage;
import kr.hyosang.android.penfo.R;
import kr.hyosang.android.penfo.SharedObject;
import kr.hyosang.android.penfo.adapter.FreeboardListAdapter;
import kr.hyosang.android.penfo.data.Article;
import kr.hyosang.android.penfo.data.ArticleViewData;
import kr.hyosang.android.penfo.data.Comment;
import kr.hyosang.android.penfo.parser.FreeBoardParser;
import kr.hyosang.android.penfo.processor.BaseProcessor;
import kr.hyosang.android.penfo.processor.ProcessorListener;
import kr.hyosang.android.penfo.processor.SendComment;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

public class FreeBoardActivity extends BoardBase<ArticleViewData> implements ProcessorListener<ArticleViewData> {
	Context mContext;
	
	BaseProcessor<Void, ArticleViewData> mProcessor;
	
	public ImageView mLoadingImg;
	public ScrollView mMainScroll;
	public TextView mContent;
	public LinearLayout mAttachments;
	public LinearLayout mArticleArea;
	public ImageView mProfile;
	public TextView mSubject;
	public TextView mWriter;
	public TextView mRegdate;
	public TextView mHitcount;
	public LinearLayout mCommentList;
	public LinearLayout mWriteComment;
	public EditText mWriteCommentText;
	public Button mWriteCommentSubmit;
	public ListView mArticleList;
	public FreeboardListAdapter mListAdapter;
	public Button mPrevButton;
	public Button mNextButton;
	
	public HttpImage profileLoader = null;
	public HttpImage [] attachLoader = null;
	
	public FreeBoardActivity() {
		this.boardId = "free";
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.freeboard);
		
		mContext = getApplicationContext();
		
		Intent i = getIntent();
		String strTmp;
		
		strTmp = i.getStringExtra("no");
		if(strTmp != null) {
			this.setNo(strTmp);
		}
		
		strTmp = i.getStringExtra("page");
		if(strTmp != null) {
			this.setPage(strTmp);
		}
		
		//ViewHolder
		mLoadingImg = (ImageView)findViewById(R.id.loadingImg);
		mMainScroll = (ScrollView)findViewById(R.id.mainScrollView);
		mArticleArea = (LinearLayout)findViewById(R.id.articleArea);
		mContent = (TextView)findViewById(R.id.freeContent);
		mAttachments = (LinearLayout)findViewById(R.id.freeAttachments);
		mProfile = (ImageView)findViewById(R.id.profileImage);
		mSubject = (TextView)findViewById(R.id.boardSubject);
		mWriter = (TextView)findViewById(R.id.boardWriter);
		mRegdate = (TextView)findViewById(R.id.boardRegdate);
		mHitcount = (TextView)findViewById(R.id.boardHitcount);
		mCommentList = (LinearLayout)findViewById(R.id.freeComment);
		mWriteComment = (LinearLayout)findViewById(R.id.writeComment);
		mWriteCommentText = (EditText)findViewById(R.id.writeCommentText);
		mWriteCommentSubmit = (Button)findViewById(R.id.writeCommentSubmit);
		mArticleList = (ListView)findViewById(R.id.articleList);
		mPrevButton = (Button)findViewById(R.id.listPrevButton);
		mNextButton = (Button)findViewById(R.id.listNextButton);
		
		mSubject.setSelected(true);
		mContent.setMovementMethod(LinkMovementMethod.getInstance());
		
		mListAdapter = new FreeboardListAdapter();
		mArticleList.setAdapter(mListAdapter);
		
		mWriteCommentText.setImeOptions(EditorInfo.IME_ACTION_SEND);
		mWriteCommentText.setOnEditorActionListener(new OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2)
            {
                if(arg1 == EditorInfo.IME_ACTION_SEND) {
                    sendComment();
                    return true;
                }
                return false;
            }
		    
		});
		
		mArticleList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				Article article = (Article)mListAdapter.getItem(arg2);
				
				Intent i = new Intent(FreeBoardActivity.this, FreeBoardActivity.class);
				i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				i.putExtra("no", article.no);
				i.putExtra("page", article.nListPage);
				startActivity(i);
			}
		});
		
		mWriteCommentSubmit.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0)
            {
                sendComment();
            }
		    
		});
		
		mPrevButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				int nPage = getPage();
				if(nPage > 1) {
					nPage--;
					Intent i = new Intent(FreeBoardActivity.this, FreeBoardActivity.class);
					i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					i.putExtra("page", Integer.toString(nPage));
					startActivity(i);
				}else {
					//no prev page...
				}
			}
		});
		
		mNextButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				//TODO cancel previous processor...
				
				mProcessor = new BaseProcessor<Void, ArticleViewData>();
				mProcessor.setListener(FreeBoardActivity.this);
				mProcessor.setParser(new FreeBoardParser());
				mProcessor.execute(getNextPageURL());
			}
		});
		
		loadPage();
		
	}
	
	public void sendComment() {
        SendComment sender = new SendComment();
        boolean bResult = sender.submit(FreeBoardActivity.this.boardId, FreeBoardActivity.this.getNo(), mWriteCommentText.getText().toString());
        
        if(bResult) {
            InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromInputMethod(mWriteCommentText.getApplicationWindowToken(), 0);
            loadPage();
        }
	}
	
	@Override
	public void refresh() {
	    //화면 클리어
	    mCommentList.removeAllViews();
	    mAttachments.removeAllViews();
	    loadPage();
	}
	
	public void loadPage() {
	    mMainScroll.setVisibility(View.GONE);
	    mLoadingImg.setVisibility(View.VISIBLE);
	    mLoadingImg.setImageResource(R.drawable.loading);
	    
	    new Handler().postDelayed(new Runnable() {
            @Override
            public void run()
            {
                ((AnimationDrawable)mLoadingImg.getDrawable()).start();
            }
	    }, 300);
	    
	    
        mProcessor = new BaseProcessor<Void, ArticleViewData>();
        mProcessor.setListener(this);
        mProcessor.setParser(new FreeBoardParser());
        mProcessor.execute(getLoadURL());
	}
	
	/**
	 * Processor Listener begin
	 */
	
	public void onComplete(ArticleViewData data) {
		LayoutParams lp;
		
        mMainScroll.setVisibility(View.VISIBLE);
        mLoadingImg.setVisibility(View.GONE);
		
		
		if(data.thisArticle != null) {
			mSubject.setText(data.thisArticle.subject);
			mWriter.setText(data.thisArticle.writer);
			mRegdate.setText(data.thisArticle.regdate);
			mHitcount.setText(data.thisArticle.hitcount + " hits");
			
			mContent.setText(Html.fromHtml(data.thisArticle.htmlContent));
			
			//comments
			LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			
			if(data.thisArticle.comment != null) {
				mCommentList.setVisibility(View.VISIBLE);
				for(Comment c : data.thisArticle.comment) {
					View commentView = inflater.inflate(R.layout.comment_item, null);
					((TextView)commentView.findViewById(R.id.commentWriter)).setText(c.writerName);
					((TextView)commentView.findViewById(R.id.commentRegdate)).setText(String.format("%s %s", c.writeDate, c.writeTime));
					((TextView)commentView.findViewById(R.id.comment)).setText(Html.fromHtml(c.comment));
					
					mCommentList.addView(commentView);
					
					Log.d("penfo", "Comment is " + c.comment);
				}
			}else {
				mCommentList.setVisibility(View.INVISIBLE);
			}
			//Profile thumbnail
			profileLoader = new HttpImage(mProfile, Definition.URL.TOP + data.thisArticle.profileUrl);
			profileLoader.load();
			
			
			lp = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
			
			if(data.thisArticle.attachments != null) {
				int size = data.thisArticle.attachments.size();
				
				attachLoader = new HttpImage[size];
				
				for(int i=0;i<size;i++) {
					String attach = data.thisArticle.attachments.get(i);
					
					ImageView attachView = new ImageView(mContext);
					attachView.setLayoutParams(lp);
					mAttachments.addView(attachView);
					
					attachLoader[i] = new HttpImage(attachView, Definition.URL.TOP + attach);
					attachLoader[i].setLayoutScaleType(HttpImage.SCALETYPE_MAXIMUM_WIDTH);
					attachLoader[i].load();
				}
			}
			
			mMainScroll.requestChildFocus(null, mProfile);
		}else {
			mArticleArea.setVisibility(View.GONE);
		}
		
		if(SharedObject.getInstance().bLogin) {
		    mWriteComment.setVisibility(View.VISIBLE);
		}else {
		    mWriteComment.setVisibility(View.INVISIBLE);
		}
		
		ArrayList<Article> list = data.getArticleList();
		for(Article a : list) {
			a.nListPage = Integer.toString(getPage());
		}
		
		mListAdapter.setData(list);
		mListAdapter.notifyDataSetChanged();
		
		lp = mArticleList.getLayoutParams();
		lp.height = mListAdapter.getListHeight(this);
		mArticleList.setLayoutParams(lp);
	}
	/**
	 * Processor Listener end
	 */

}
